import json
import pickle
import re
from collections import defaultdict

import tornado
from tornado.escape import json_encode
from tornado.web import RequestHandler, HTTPError
from myredis.myconnect import r
from .authentications import authenticated


class BaseHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        allow_list = [
            'http://www.mytaotao.cn:8001',
        ]
        if 'Origin' in self.request.headers:
            Origin = self.request.headers['Origin']
            if Origin in allow_list:
                self.set_header("access-control-allow-origin",Origin)
                self.set_header("Access-Control-Allow-Headers", "Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With")
                #self.set_header('Access-Control-Allow-Methods', "GET,POST,DELETE,PUT,OPTIONS")
                self.set_header('access-control-allow-credentials', "true")
                print("aaaaaaaaaaaaaaaa")
                print(self.request.method)


class MsgHandler(BaseHandler):
    # def initialize(self,database):
    #     pass
        #self.database = database

    @tornado.gen.coroutine
    def get(self,username):
        #获取未接受的信息
        msgliststr= ''
        msgpattren = "chat||"+username+"||notrecv||*"

        msgKeysList = r.keys(pattern=msgpattren)
        groupdict=defaultdict(list)
        for msgKey in msgKeysList:#该用户下所有的分组
            aa=msgKey.decode('utf-8')
            grouplist = aa.split('||')
            groupname = grouplist[-1]#聊天组名称
            msgnum = r.llen(msgKey)#聊天组消息数
            rmsglist = r.lrange(msgKey, 0, msgnum)#该用户该分组的消息列表
            for msg in rmsglist:
                onemsg = json.loads(msg)
                onedict = json.loads(onemsg)
                msgliststr += onemsg
                if msg is not rmsglist[-1]:
                    msgliststr += ','
                groupdict[groupname].append(onedict)
            if msgliststr:
                pass
                result = '[' + msgliststr + ']'
            #groupdict[groupname].append(msgliststr)

        print(groupdict)
        self.set_header('Content-type','application/json')
        self.write(groupdict)

    @tornado.gen.coroutine
    def options(self,username=''):
        if self.request.method not in ['OPTIONS','GET']:
            return HTTPError(405)





